package uu.tools.collection;

import java.lang.reflect.Array;

public class FixedSizeSynchronizedArrayQueue<T> {
    private Object[] list;
    private Class cls;
    private boolean full;
    private int index = 0;
    private int lastIndex;

    public FixedSizeSynchronizedArrayQueue(int size, Class cls) {
        list = new Object[size];
        lastIndex = size - 1;
        this.cls = cls;
    }

    public synchronized void add(T t) {
        list[index++] = t;
        if (index > lastIndex) {
            index = 0;
            if (!full) full = true;
        }
    }

    public synchronized T[] all() {
        Object[] rs;
        if (full) {
            rs = (Object[])Array.newInstance(cls, list.length);
            int rsi = 0;
            for (int i = index; i < list.length; i++) {
                rs[rsi++] = list[i];
            }
            for (int i = 0; i < index; i++) {
                rs[rsi++] = list[i];
            }
        } else {
            rs = (Object[])Array.newInstance(cls, index);
            for (int i = 0; i < index; i++) {
                rs[i] = list[i];
            }
        }
        return (T[])rs;
    }

    public synchronized Object[] toArray() {
        Object[] rs;
        if (full) {
            rs = new Object[list.length];
            int rsi = 0;
            for (int i = index; i < list.length; i++) {
                rs[rsi++] = list[i];
            }
            for (int i = 0; i < index; i++) {
                rs[rsi++] = list[i];
            }
        } else {
            rs = new Object[index];
            for (int i = 0; i < index; i++) {
                rs[i] = list[i];
            }
        }
        return rs;
    }
}
